package ar.com.angrymachine.gameui;

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Timer;
import java.util.TimerTask;

public abstract class GameApp extends Frame implements WindowListener
{
    public GameCanvas gameCanvas = null;
	protected Timer timer;
	
	private class MainLoop extends TimerTask
	{
		private GameApp app;
		MainLoop(GameApp app)
		{
			this.app = app;
		}
		
		public void run()
		{
			//TODO: this is not the right question to ask
            if(gameCanvas.isValid())
            {
                gameCanvas.run();
                app.run();
            }
            else
            {
            	timer.cancel();
            }
		}
	}
		
	public abstract void run();
	public abstract void onExit();
	public abstract void onInit();
	
	public void show(Theme theme, String title, String iconFile,  int width, int height, int updateRate)
	{
		setSize(width, height);
		addWindowListener(this);
		gameCanvas = new GameCanvas(theme);
		add(gameCanvas);
		doLayout();
		Utils.centerWindow(this);
		setResizable(false);
		setTitle(title);
		if (iconFile != null)
		{
			setIconImage(gameCanvas.loadImage(iconFile));
		}
		setVisible(true);
		onInit();
        timer = new Timer();
        timer.schedule(new MainLoop(this), 0, updateRate);
	}
	
	public void windowActivated(WindowEvent arg0)
	{
	}
	
	public void windowClosed(WindowEvent arg0)
	{
	}
	
	public void windowClosing(WindowEvent arg0)
	{
		onExit();
		setVisible(false);
		dispose();
		System.exit(0);
	}
	public void windowDeactivated(WindowEvent arg0)
	{
	}
	
	public void windowDeiconified(WindowEvent arg0)
	{
	}
	
	public void windowIconified(WindowEvent arg0)
	{
	}
	
	public void windowOpened(WindowEvent arg0)
	{
	}
}
